﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;

namespace TwitterAPI
{
    internal class Connection
    {
        private Uri twitterUri = new Uri("http://www.twitter.com");
        ICredentials credentials;
		CookieContainer cookies = new CookieContainer();

		internal Connection(ICredentials credentials)
		{
			this.credentials = credentials;
            if (!ValidateCredentials(credentials.GetCredential(twitterUri, "").UserName, credentials.GetCredential(twitterUri, "").Password))
            {
                throw new InvalidOperationException("The supplied user name or password is incorrect");
            }
		}

        public bool ValidateCredentials(string username, string password)
        {
            var request = CreateRequest("http://twitter.com/account/verify_credentials.xml");

            try
            {
                using (var response = request.GetResponse())
                {
                    using (var reader = XmlReader.Create(response.GetResponseStream()))
                    {
                        if (reader.ReadToDescendant("user") &&
                            reader.ReadToDescendant("screen_name") &&
                            reader.ReadElementContentAsString() == username)
                        {
                            return true;
                        }
                    }
                }
            }
            catch(WebException)
            {
                return false;
            }

            return false;
        }

        internal WebRequest CreateRequest(string uri)
        {
            WebRequest request = WebRequest.Create(uri);
            HttpWebRequest http = request as HttpWebRequest;
            if (http != null)
            {
                http.CookieContainer = cookies;
            }
            request.Credentials = credentials;
            return request;
        }

        internal WebRequest CreateRequestWithUserName(string uri)
        {
            return CreateRequest(string.Format(uri, credentials.GetCredential(twitterUri, "").UserName));
        }
    }
}
